---
import Layout from '../layouts/Layout.astro'
---

<Layout title="Password Protection">
  <main class="h-screen col-fcc">
    <div class="op-30">Please input password</div>
    <div id="input_container" class="mt-4 flex">
      <input id="password_input" type="password" class="gpt-password-input" />
      <div id="submit" class="gpt-password-submit">
        <div class="i-carbon-arrow-right" />
      </div>
    </div>
  </main>
</Layout>

<script>
const inputContainer = document.getElementById('input_container') as HTMLDivElement
const input = document.getElementById('password_input') as HTMLInputElement
const submitButton = document.getElementById('submit') as HTMLDivElement

input.onkeydown = async(event) => {
  if (event.key === 'Enter')
    handleSubmit()
}
submitButton.onclick = handleSubmit

async function handleSubmit() {
  const password = input.value
  const response = await fetch('/api/auth', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      pass: password,
    }),
  })
  const responseJson = await response.json()
  if (responseJson.code === 0) {
    localStorage.setItem('pass', password)
    window.location.href = '/'
  } else {
    inputContainer.classList.add('invalid')
    setTimeout(() => {
      inputContainer.classList.remove('invalid')
    }, 300)
  }
}
</script>

<style>
@keyframes shake {
  0% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(0.5rem);
  }
  75% {
    transform: translateX(-0.5rem);
  }
  100% {
    transform: translateX(0);
  }
}

.invalid {
  animation: shake 0.2s ease-in-out 0s 2;
}
</style>
